<template>
  <div class="create-return-form">
    <form @submit.prevent="submitForm">
      <!-- 原订单信息 -->
      <div class="form-section">
        <h3>原订单信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>原订单编号 *</label>
            <div class="search-input">
              <input v-model="originalOrderCode" type="text" placeholder="请输入原订单编号" @blur="loadOriginalOrder" required>
              <button type="button" @click="searchOriginalOrder">
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 原订单详情 -->
        <div v-if="originalOrder" class="original-order-info">
          <h4>原订单详情</h4>
          <div class="order-info-grid">
            <div class="info-item">
              <label>订单编号</label>
              <span>{{ originalOrder.orderCode }}</span>
            </div>
            <div class="info-item">
              <label>客户姓名</label>
              <span>{{ originalOrder.customerName }}</span>
            </div>
            <div class="info-item">
              <label>联系电话</label>
              <span>{{ originalOrder.customerPhone }}</span>
            </div>
            <div class="info-item">
              <label>订单金额</label>
              <span>¥{{ (originalOrder.finalAmount || 0).toFixed(2) }}</span>
            </div>
            <div class="info-item">
              <label>订单日期</label>
              <span>{{ formatDate(originalOrder.orderDate) }}</span>
            </div>
            <div class="info-item">
              <label>订单状态</label>
              <span class="status" :class="(originalOrder.orderStatus || originalOrder.status || '').toLowerCase()">
                {{ getStatusText(originalOrder.status) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 退货商品选择 -->
      <div v-if="originalOrder" class="form-section">
        <h3>退货商品选择</h3>
        <div class="return-items">
          <div v-for="(item, index) in originalOrder.items" :key="index" class="return-item">
            <div class="item-checkbox">
              <input 
                :id="`item-${index}`" 
                v-model="selectedItems" 
                :value="item" 
                type="checkbox"
                @change="updateReturnSummary"
              >
              <label :for="`item-${index}`"></label>
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-details">
                <span class="item-code">{{ item.productCode }}</span>
                <span class="item-price">¥{{ (item.unitPrice || 0).toFixed(2) }}</span>
                <span class="item-quantity">数量: {{ item.quantity }}</span>
              </div>
            </div>
            <div class="item-return-quantity">
              <label>退货数量</label>
              <input 
                v-model.number="item.returnQuantity" 
                type="number" 
                min="0" 
                :max="item.quantity"
                @change="updateReturnSummary"
              >
            </div>
            <div class="item-return-amount">
              <label>退货金额</label>
              <span class="return-amount">¥{{ ((item.returnQuantity || 0) * (item.unitPrice || 0) * (item.discountRate || 0)).toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 退货原因 -->
      <div class="form-section">
        <h3>退货原因</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>退货原因 *</label>
            <select v-model="form.reason" required>
              <option value="">请选择退货原因</option>
              <option value="商品质量问题">商品质量问题</option>
              <option value="商品损坏">商品损坏</option>
              <option value="商品不符">商品不符</option>
              <option value="客户不满意">客户不满意</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div class="form-group">
            <label>详细说明</label>
            <textarea v-model="form.description" placeholder="请详细说明退货原因"></textarea>
          </div>
        </div>
      </div>

      <!-- 退货汇总 -->
      <div v-if="returnSummary.totalQuantity > 0" class="form-section">
        <h3>退货汇总</h3>
        <div class="return-summary">
          <div class="summary-row">
            <span>退货商品数量:</span>
            <span>{{ returnSummary.totalQuantity }} 件</span>
          </div>
          <div class="summary-row">
            <span>退货商品金额:</span>
            <span>¥{{ (returnSummary.totalAmount || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>预计退款金额:</span>
            <span>¥{{ (returnSummary.refundAmount || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>积分退还:</span>
            <span>{{ returnSummary.pointsRefund }} 积分</span>
          </div>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <h3>其他信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>联系人</label>
            <input v-model="form.contactName" type="text" placeholder="请输入联系人姓名">
          </div>
          <div class="form-group">
            <label>联系电话</label>
            <input v-model="form.contactPhone" type="tel" placeholder="请输入联系电话">
          </div>
          <div class="form-group">
            <label>退货地址</label>
            <textarea v-model="form.returnAddress" placeholder="请输入退货地址"></textarea>
          </div>
          <div class="form-group">
            <label>备注</label>
            <textarea v-model="form.remark" placeholder="请输入备注信息"></textarea>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="button" class="btn-cancel" @click="$emit('close')">
          取消
        </button>
        <button type="submit" class="btn-submit" :disabled="!isFormValid">
          <i class="fas fa-save"></i>
          创建退货单
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, computed } from 'vue'

export default {
  name: 'CreateReturnForm',
  emits: ['close', 'success'],
  setup(props, { emit }) {
    const originalOrderCode = ref('')
    const originalOrder = ref(null)
    const selectedItems = ref([])
    
    // 表单数据
    const form = ref({
      reason: '',
      description: '',
      contactName: '',
      contactPhone: '',
      returnAddress: '',
      remark: ''
    })
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statuses = {
        'Pending': '待处理',
        'Processing': '处理中',
        'Shipped': '已发货',
        'Delivered': '已送达',
        'Cancelled': '已取消'
      }
      return statuses[status] || status
    }
    
    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    // 搜索原订单
    const searchOriginalOrder = () => {
      loadOriginalOrder()
    }
    
    // 加载原订单信息
    const loadOriginalOrder = async () => {
      if (!originalOrderCode.value) return
      
      try {
        const response = await fetch(`/api/retail/orders/by-code/${originalOrderCode.value}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          
          // 检查是否有订单明细数据
          let orderItems = []
          if (data.orderItems && data.orderItems.length > 0) {
            orderItems = data.orderItems
          } else if (data.items && data.items.length > 0) {
            orderItems = data.items
          } else {
            // 如果没有明细数据，使用模拟数据
            console.warn('订单没有明细数据，使用模拟数据')
            orderItems = [
              {
                id: 1,
                productId: 1,
                productName: 'Galaxy S22',
                productCode: 'GALAXYS22',
                unitPrice: 5299.00,
                quantity: 1,
                discountRate: 0.90
              }
            ]
          }
          
          originalOrder.value = {
            ...data,
            items: orderItems.map(item => ({
              ...item,
              returnQuantity: 0
            }))
          }
        } else {
          console.error('加载原订单信息失败:', response.statusText)
          // 使用模拟数据作为备选
          if (originalOrderCode.value === 'RSO202409001') {
            originalOrder.value = {
              id: 1,
              orderCode: 'RSO202409001',
              customerName: '张三',
              customerPhone: '13800138000',
              finalAmount: 6225.30,
              orderDate: '2024-09-01',
              status: 'Delivered',
              items: [
                {
                  productId: 1,
                  productName: 'iPhone 13',
                  productCode: 'IPHONE13',
                  unitPrice: 5800,
                  quantity: 1,
                  discountRate: 0.95,
                  returnQuantity: 0
                }
              ]
            }
          } else if (originalOrderCode.value === 'RSO202409002') {
            originalOrder.value = {
              id: 2,
              orderCode: 'RSO202409002',
              customerName: '李四',
              customerPhone: '13900139000',
              finalAmount: 12451.47,
              orderDate: '2024-09-02',
              status: 'Shipped',
              items: [
                {
                  productId: 1,
                  productName: 'iPhone 13',
                  productCode: 'IPHONE13',
                  unitPrice: 5800,
                  quantity: 1,
                  discountRate: 0.95,
                  returnQuantity: 0
                },
                {
                  productId: 2,
                  productName: 'MacBook Pro 13寸',
                  productCode: 'MACBOOKPRO',
                  unitPrice: 9999,
                  quantity: 1,
                  discountRate: 0.95,
                  returnQuantity: 0
                }
              ]
            }
          } else {
            originalOrder.value = null
            alert('未找到该订单，请检查订单编号')
          }
        }
      } catch (error) {
        console.error('加载原订单信息失败:', error)
        originalOrder.value = null
        alert('加载订单信息失败，请检查网络连接')
      }
    }
    
    // 更新退货汇总
    const updateReturnSummary = () => {
      // 触发计算属性更新
    }
    
    // 退货汇总计算
    const returnSummary = computed(() => {
      let totalQuantity = 0
      let totalAmount = 0
      let refundAmount = 0
      let pointsRefund = 0
      
      selectedItems.value.forEach(item => {
        if (item.returnQuantity > 0) {
          totalQuantity += item.returnQuantity
          const itemAmount = item.returnQuantity * item.unitPrice * item.discountRate
          totalAmount += itemAmount
          refundAmount += itemAmount * 1.13 // 包含税费
          pointsRefund += Math.floor(itemAmount * 0.01) // 1%积分
        }
      })
      
      return {
        totalQuantity,
        totalAmount,
        refundAmount,
        pointsRefund
      }
    })
    
    // 表单验证
    const isFormValid = computed(() => {
      return originalOrder.value && 
             form.value.reason && 
             returnSummary.value.totalQuantity > 0
    })
    
    // 提交表单
    const submitForm = async () => {
      try {
        const returnData = {
          originalOrderId: originalOrder.value.id,
          originalOrderCode: originalOrder.value.orderCode,
          customerId: originalOrder.value.customerId,
          customerName: originalOrder.value.customerName,
          customerPhone: originalOrder.value.customerPhone,
          returnItems: selectedItems.value.filter(item => item.returnQuantity > 0),
          returnAmount: returnSummary.value.totalAmount,
          refundAmount: returnSummary.value.refundAmount,
          pointsRefund: returnSummary.value.pointsRefund,
          reason: form.value.reason,
          description: form.value.description,
          contactName: form.value.contactName,
          contactPhone: form.value.contactPhone,
          returnAddress: form.value.returnAddress,
          remark: form.value.remark,
          returnDate: new Date().toISOString(),
          returnStatus: 'Pending'
        }
        
        console.log('发送退货单数据:', returnData)
        
        const response = await fetch('/api/retail/returns', {
          method: 'POST',
          headers: { 
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(returnData)
        })
        
        if (response.ok) {
          const result = await response.json()
          console.log('创建退货单成功:', result)
          alert('退货单创建成功！')
          emit('success')
        } else {
          let errorMessage = response.statusText
          try {
            const errorData = await response.json()
            errorMessage = errorData.message || errorData.error || response.statusText
            console.error('创建退货单失败:', errorData)
          } catch (parseError) {
            console.error('解析错误响应失败:', parseError)
            console.error('响应状态:', response.status, response.statusText)
          }
          alert(`创建退货单失败: ${errorMessage}`)
        }
      } catch (error) {
        console.error('创建退货单失败:', error)
        alert('创建退货单失败，请检查网络连接')
      }
    }
    
    return {
      originalOrderCode,
      originalOrder,
      selectedItems,
      form,
      returnSummary,
      isFormValid,
      getStatusText,
      formatDate,
      searchOriginalOrder,
      loadOriginalOrder,
      updateReturnSummary,
      submitForm
    }
  }
}
</script>

<style scoped>
.create-return-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
}

.form-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.875rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #f093fb;
  box-shadow: 0 0 0 3px rgba(240, 147, 251, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.search-input {
  display: flex;
  gap: 8px;
}

.search-input input {
  flex: 1;
}

.search-input button {
  padding: 10px 16px;
  background: #f093fb;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.original-order-info {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
  margin-top: 16px;
}

.original-order-info h4 {
  font-size: 1rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 12px;
}

.order-info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.info-item span {
  color: #2d3748;
  font-size: 0.875rem;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.status.delivered {
  background: #e6fffa;
  color: #234e52;
}

.status.shipped {
  background: #c6f6d5;
  color: #22543d;
}

.return-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.return-item {
  display: grid;
  grid-template-columns: auto 2fr 1fr 1fr;
  gap: 16px;
  align-items: center;
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.item-checkbox {
  display: flex;
  align-items: center;
}

.item-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  margin: 0;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-name {
  font-weight: 500;
  color: #2d3748;
}

.item-details {
  display: flex;
  gap: 12px;
  font-size: 0.875rem;
  color: #718096;
}

.item-return-quantity input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  text-align: center;
}

.item-return-amount {
  text-align: right;
}

.return-amount {
  font-weight: 600;
  color: #2d3748;
  font-size: 1.1rem;
}

.return-summary {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.summary-row:last-child {
  border-bottom: none;
  border-top: 2px solid #e2e8f0;
  margin-top: 8px;
  padding-top: 12px;
  font-weight: 600;
  font-size: 1.1rem;
  color: #2d3748;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px 0;
}

.btn-cancel,
.btn-submit {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #e2e8f0;
  color: #4a5568;
}

.btn-submit {
  background: #f093fb;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-cancel:hover,
.btn-submit:hover:not(:disabled) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .order-info-grid {
    grid-template-columns: 1fr;
  }
  
  .return-item {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
